﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DatabaseCore
{
    public class ProductQueueMappedDao : IProductQueueMappedDao
    {
        public bool Insert(ProductQueueMapped entity)
        {
            using (var ctx = new ExportDBEntities())
            {
                ctx.ProductQueueMapped.Add(entity);
                return ctx.SaveChanges() > 0;
            }
        }

        public bool InsertCollection(List<ProductQueueMapped> entity)
        {
            using (var ctx = new ExportDBEntities())
            {
                foreach (var item in entity)
                {
                    item.Date = DateTime.Now;
                    ctx.ProductQueueMapped.Add(item);
                }
                return ctx.SaveChanges() > 0;
            }
        }

        public bool Delete(ProductQueueMapped entity)
        {
            using (var ctx = new ExportDBEntities())
            {
                ctx.ProductQueueMapped.Remove(entity);
                return ctx.SaveChanges() > 0;
            }
        }

        public ProductQueueMapped GetByOrderNoAndMaterialNo(string orderNo, string materialNo)
        {
            using (var ctx = new ExportDBEntities())
            {
                var queue = from q in ctx.ProductQueueMapped
                            where q.OrderNo == orderNo
                                && q.ProductId == materialNo
                            select q;

                if (queue == null || queue.Count() == 0)
                    return null;

                return queue.FirstOrDefault();
            }
        }

        public bool DeleteByOrderNoAndMaterialNoAndPlantCode(string orderNo, string materialNo, string plantCode)
        {
            using (var ctx = new ExportDBEntities())
            {
                var queue = from q in ctx.ProductQueueMapped
                            where q.OrderNo == orderNo
                                && q.ProductId == materialNo
                                && q.PlantCode == plantCode
                            select q;

                if (queue == null || queue.Count() == 0)
                    return false;

                ctx.ProductQueueMapped.Remove(queue.FirstOrDefault());
                return ctx.SaveChanges() > 0;
            }
        }
    }
}
